import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from 'views/Home'
import { getToken } from 'utils'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  }, {
    path: '/home',
    name: 'home',
    meta: {
      islogin: false,
      keepAlive: true
    },
    component: Home
  },
  {
    path: '/cart',
    name: 'cart',
    meta: {
      islogin: true
    },
    component: () => import('views/Cart')
  },
  {
    path: '/cate',
    name: 'cate',
    meta: {
      islogin: false
    },
    component: () => import('views/Cate')
  },
  {
    path: '/user',
    name: 'user',
    meta: {
      islogin: true
    },
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ 'views/User')
  },
  {
    path: '/detail',
    name: 'detail',
    meta: {
      islogin: false
    },
    component: () => import('views/Detail')
  },
  {
    path: '/itemlist/:itemid/:itemname',
    name: 'itemlist',
    meta: {
      islogin: false
    },
    component: () => import('views/Itemlist')
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      islogin: false
    },
    component: () => import('views/Login')
  },
  {
    path: '/contlist',
    name: 'contlist',
    meta: {
      islogin: true
    },
    component: () => import('views/ContactsList')
  },
  {
    path: '/addcont',
    name: 'addcont',
    meta: {
      islogin: true
    },
    component: () => import('views/AddContacts')
  },
  {
    path: '/updatecont',
    name: 'updatecont',
    meta: {
      islogin: true
    },
    component: () => import('views/UpdateContacts')
  },
  {
    path: '/register',
    name: 'register',
    meta: {
      islogin: false
    },
    component: () => import('views/Register')
  },
  {
    path: '/confirmorder',
    name: 'confirmorder',
    meta: {
      islogin: true
    },
    component: () => import('views/ConfirmOrder')
  },
  {
    path: '/search',
    name: 'search',
    meta: {
      islogin: false
    },
    component: () => import('views/Search')
  },
  {
    path: '/searchitems',
    name: 'searchitems',
    meta: {
      islogin: false
    },
    component: () => import('views/SearchItems')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  localStorage.setItem('boforeFrom', from.path)
  if (!to.meta.islogin) {
    next()
  } else {
    if (getToken()) {
      next()
    } else {
      Toast.success({
        message: '请先登录',
        duration: 1000,
        onClose: () => {
          next({
            path: '/login',
            query: {
              from: to.path
            }
          })
        }
      })
    }
  }
})

export default router
